package com.dayaokeji.rhythmschoolstudent.client.mine;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.boxing.BoxingUtil;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.ApiConstantKt;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.ResetMobileActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.bean.GenderBean;
import com.dayaokeji.rhythmschoolstudent.event.ResetMobileEvent;
import com.dayaokeji.rhythmschoolstudent.event.UpdateUserInfoEvent;
import com.dayaokeji.rhythmschoolstudent.glide.GlideUrlModel;
import com.dayaokeji.rhythmschoolstudent.utils.FileUtil;
import com.dayaokeji.rhythmschoolstudent.utils.FilenameUtils;
import com.dayaokeji.rhythmschoolstudent.utils.PermissionUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.ResourceApi;
import com.dayaokeji.server_api.api.UserApi;
import com.dayaokeji.server_api.domain.UpdateUserInfo;
import com.dayaokeji.server_api.domain.UserInfo;
import com.dayaokeji.server_api.utils.FileFunctionFlag;
import com.orhanobut.logger.Logger;
import com.othershe.library.NiceImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;

/**
 * 个人资料
 */
public class PersonalInfoActivity extends BaseActivity {


    private static final int CHOOSE_AVATAR_IMAGE_REQUEST_CODE = 1001;

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_job_number)
    TextView tvJobNumber;
    @BindView(R.id.tv_user_student_id)
    TextView tvUserStudentId;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.tv_school)
    TextView tvSchool;
    @BindView(R.id.tv_department)
    TextView tvDepartment;
    @BindView(R.id.tv_user_gender)
    TextView tvUserGender;
    @BindView(R.id.tv_professional)
    TextView tvProfeessional;
    @BindView(R.id.tv_class)
    TextView tvClass;
    @BindView(R.id.iv_user_avatar)
    NiceImageView ivUserAvatar;

    private UserInfo userInfo;
    private static final UserApi userApi = ApiUtils.getApi(UserApi.class);
    private static final ResourceApi resourceApi = ApiUtils.getApi(ResourceApi.class);
    private Call<ServerResponse<Void>> updateCall;
    private UpdateUserInfo updateUserInfo;
    private Call<ServerResponse<List<Integer>>> uploadAvatarCall;
    private boolean isSetting = false;
    private boolean isUpdateAvatar = false;
    private MenuItem settingMenuItem;
    private Call<ServerResponse<Void>> syncStudentInfoCall;
    private Call<ServerResponse<UserInfo>> userDetailCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_personal_info);
        setSupportActionBar(toolbar);
        EventBus.getDefault().register(this);
        initData();
    }

    private void initData() {
        userInfo = UserUtils.getUserInfo();
        if (userInfo == null) {
            ToastUtils.warning("未获取到用户信息");
            ActivityStackManager.finish();
            return;
        }
        updateUserInfo = new UpdateUserInfo();
        updateUserInfo.setId(userInfo.getId());
        tvUserName.setText(userInfo.getName());
        tvJobNumber.setText(userInfo.getWorkNo());
        tvUserStudentId.setText(getString(R.string.p_student_id,userInfo.getWorkNo()));
        tvMobile.setText(userInfo.getPhone());
        tvSchool.setText(userInfo.getUniversityName());
        tvDepartment.setText(userInfo.getFacultyName());
        tvUserGender.setText(UserUtils.getGenderName(userInfo.getSex()));
        tvProfeessional.setText(userInfo.getMajorName());
        tvClass.setText(userInfo.getClassName());
        withGlide().load(new GlideUrlModel(ApiConstantKt.getRemoteImageUrl()+(TextUtils.isEmpty(userInfo.getPictureId()) ? "" : userInfo.getPictureId()))).into(ivUserAvatar);
    }

    @OnClick({
            R.id.iv_user_avatar,
            R.id.ll_update_gender,
            R.id.ll_update_mobile,
            R.id.ll_department,
            R.id.ll_professional,
            R.id.ll_class
    })
    public void onClick(View view) {
        isUpdateAvatar = false;
        switch (view.getId()) {
            case R.id.iv_user_avatar:
                if (isSetting) {
                    isUpdateAvatar = true;
                    addDisposable(PermissionUtil.checkCameraPermission(this).subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                BoxingUtil.startSingleChooseImageCrop(PersonalInfoActivity.this,CHOOSE_AVATAR_IMAGE_REQUEST_CODE);
                            }
                        }
                    }));
                }
                break;
            case R.id.ll_update_gender:
                if (isSetting){
                    updateGender();
                }
                break;
            case R.id.ll_update_mobile:
                if (isSetting) {
                    ResetMobileActivity.Companion.navigation(PersonalInfoActivity.this);
                }
                break;
            case R.id.ll_department:
            case R.id.ll_professional:
            case R.id.ll_class:
                if (isSetting){
                    syncStudentInfo();
                }
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.personal_info, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        settingMenuItem = menu.findItem(R.id.menu_person_info);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_person_info:
                setPersonalInfo();
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    /**
     * 同步学生信息
     */
    private void syncStudentInfo() {
        if (userInfo != null) {
            Map<String,Object> params = new HashMap<>();
            params.put("universityId", userInfo.getUniversityId());
            params.put("workNo", userInfo.getWorkNo());
            syncStudentInfoCall = userApi.syncStudentInfo(params);
            syncStudentInfoCall.enqueue(new ServerCallback<Void>(this,"正在同步...") {
                @Override
                public void onResponse(boolean success, ServerResponse<Void> response) {
                    if (success) {
                        getUserDetail();
                    }
                }
            });
        }else{
            ToastUtils.info("获取缓存用户信息失败");
        }
    }

    /**
     * 获取个人详情
     */
    private void getUserDetail() {
        if (userInfo != null) {
            userDetailCall = userApi.userDetail(Long.parseLong(userInfo.getId()));
            userDetailCall.enqueue(new ServerCallback<UserInfo>() {
                @Override
                public void onResponse(boolean success, ServerResponse<UserInfo> response) {
                    if (success) {
                        UserUtils.setUserInfo(userInfo);
                        initData();
                    }
                }
            });
        }
    }

    /**
     * setting user info
     */
    private void setPersonalInfo() {
        isSetting = !isSetting;
        if (isSetting) {
            settingMenuItem.setTitle("保存");
        }else{
            settingMenuItem.setTitle("设置");
        }
        if (isSetting) {
            tvJobNumber.setTextColor(Color.GRAY);
            tvSchool.setTextColor(Color.GRAY);

        }else{
            tvJobNumber.setTextColor(Color.parseColor("#333333"));
            tvSchool.setTextColor(Color.parseColor("#333333"));
        }
        if (!isSetting && !isUpdateAvatar) {
            update();
        }
    }

    /**
     * 更新性别
     */
    private void updateGender() {
        final List<GenderBean> genderBeans = new ArrayList<>();
        genderBeans.add(new GenderBean(1,"男"));
        genderBeans.add(new GenderBean(2,"女"));
        final OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(this, (i, i1, i2, view) -> {
            GenderBean genderBean = genderBeans.get(i);
            if (genderBean != null) {
                tvUserGender.setText(genderBean.getName());
                updateUserInfo.setSex(genderBean.getType());
            }
        })
                .setSelectOptions(1)
                .setTitleText("请选择性别")
                .build();
        optionsPickerView.setPicker(genderBeans);
        optionsPickerView.show();
    }


    /**
     * 更新用户信息
     */
    private void update() {
        updateCall = userApi.update(updateUserInfo);
        updateCall.enqueue(new ServerCallback<Void>(this,"正在更新...") {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    ToastUtils.success("更新成功");
                    userInfo.setSex(updateUserInfo.getSex());
                    UserUtils.setUserInfo(userInfo);
                    EventBus.getDefault().post(new UpdateUserInfoEvent());
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void resetMobileEvent(ResetMobileEvent resetMobileEvent) {
        if (resetMobileEvent != null) {
            if (tvMobile != null && userInfo != null) {
                userInfo.setPhone(resetMobileEvent.getResetMobile());
                UserUtils.setUserInfo(userInfo);
                tvMobile.setText(resetMobileEvent.getResetMobile());
            }
        }
    }


    @Override
    protected void onDestroy() {
        if (updateCall != null) {
            updateCall.cancel();
        }
        if (syncStudentInfoCall != null) {
            syncStudentInfoCall.cancel();
        }
        if (uploadAvatarCall != null) {
            uploadAvatarCall.cancel();
        }
        if (userDetailCall != null) {
            userDetailCall.cancel();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (CHOOSE_AVATAR_IMAGE_REQUEST_CODE == requestCode) {
            final String filePath = BoxingUtil.getResultFilePath(data);
            if (!TextUtils.isEmpty(filePath) && userInfo != null) {
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), new File(filePath));
                MultipartBody.Part filePart = MultipartBody.Part.createFormData("myfiles", FilenameUtils.getName(filePath),requestBody);
                uploadAvatarCall = resourceApi.upload(filePart,
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(FileUtil.getFileType(filePath))),
                        RequestBody.create(MediaType.parse("text/plain"), FilenameUtils.getName(filePath)),
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(FileFunctionFlag.AVATAR)),
                        RequestBody.create(MediaType.parse("text/plain"), userInfo.getId()),
                        RequestBody.create(MediaType.parse("text/plain"), String.valueOf(Boolean.TRUE.booleanValue())));
                uploadAvatarCall.enqueue(new ServerCallback<List<Integer>>(this,"正在上传头像...") {
                    @Override
                    public void onResponse(boolean success, ServerResponse<List<Integer>> response) {
                        if (success) {
                            Logger.d("updaload avatar..."+response.toString());
                            ToastUtils.success("头像上传成功");
                            if (ivUserAvatar != null) {
                                withGlide().load("file://"+filePath).into(ivUserAvatar);
                                UserInfo userInfo = UserUtils.getUserInfo();
                                if (userInfo != null) {
                                    int i = response.getBody().size() > 0 ? response.getBody().get(0) : 0;
                                    userInfo.setPictureId(String.valueOf(i));
                                }
                                UserUtils.setUserInfo(userInfo);
                                EventBus.getDefault().post(new UpdateUserInfoEvent());
                            }
                        }
                    }
                });
            }
        }
    }
}
